/**
 * idMaker
 */
function foo() {
  function* idMaker() {
    let index = 0;
    while (true) {
      yield index++;
    }
  }

  const gen = idMaker();

  console.log(gen.next().value); // 0
  console.log(gen.next().value); // 1
  console.log(gen.next().value); // 2
  console.log(gen.next().value); // 3
}
foo();

/**
 * 使用 yield* 示例
 */
function fun() {
  /**
   * i一直都是10
   * @param {*} i
   */
  function* anotherGenerator(i) {
    yield i + 1;
    yield i + 2;
    yield i + 3;
  }

  function* generator(i) {
    yield i;
    yield* anotherGenerator(i);
    yield i + 10;
  }

  const gen = generator(10);

  console.log(gen.next().value); // 10
  console.log(gen.next().value); // 11
  console.log(gen.next().value); // 12
  console.log(gen.next().value); // 13
  console.log(gen.next().value); // 20
}
// fun();

/**
 * yield 接受入参
 * 传入参数给生成器
 */
function bar() {
  function* logGenerator() {
    console.log(0);
    console.log(1, yield);
    console.log(2, yield);
    console.log(3, yield);
  }

  const gen = logGenerator();

  // next 的第一次调用从函数的开头开始执行，直到第一个 yield 语句
  gen.next(); // 0
  gen.next("pretzel"); // 1 pretzel
  gen.next("california"); // 2 california
  gen.next("mayonnaise"); // 3 mayonnaise
}
// bar();

/**
 * 生成器中的返回语句
 */
function coo() {
  function* yieldAndReturn() {
    yield "产生的值";
    return "返回的值";
    yield "不会被访问到的值";
  }

  const gen = yieldAndReturn();
  console.log(gen.next()); // { value: "产生的值", done: false }
  console.log(gen.next()); // { value: "返回的值", done: true }
  console.log(gen.next()); // { value: undefined, done: true }
}
// coo();

/**
 * 生成器作为对象属性
 */
function boo() {
  const someObj = {
    *generator() {
      yield "a";
      yield "b";
    },
  };

  const gen = someObj.generator();

  console.log(gen.next()); // { value: 'a', done: false }
  console.log(gen.next()); // { value: 'b', done: false }
  console.log(gen.next()); // { value: undefined, done: true }
}
// boo();

/**
 * 生成器作为计算属性
 */
function doo() {
  const SomeObj = {
    *[Symbol.iterator]() {
      yield "a";
      yield "b";
    },
  };

  console.log(Array.from(SomeObj)); // [ 'a', 'b' ]
}
// doo();
